package com.wx.spider.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wx.spider.common.pojo.db.WxBizNews;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;

import java.util.*;

/**
 * @author:feng
 * @create:2021-04-25 18:53
 */
@Slf4j
public class JsonUtils {
    public static List<WxBizNews> getNewFromJsonStr(String tagStr) {
        ArrayList<WxBizNews> list = new ArrayList<WxBizNews>();
        String jsonStr = StringEscapeUtils.unescapeXml(StringEscapeUtils.unescapeXml(tagStr));
        JSONObject jsonObject = null;
        try {
            jsonObject = JSON.parseObject(jsonStr);
        } catch (Exception e) {
            try {
                jsonStr = jsonStr.replaceAll("([^:])(\"\")", "$1\"");
                jsonObject = JSON.parseObject(jsonStr);
            } catch (Exception e1) {
                try {
                    jsonStr = jsonStr.replaceAll("([^:,\"\\{\\}])(\")([^:,\"\\{\\}])", "$1 $3");
                    jsonObject = JSON.parseObject(jsonStr);
                } catch (Exception e2) {
                    e2.printStackTrace();
                    log.info("==============解析json失败：===============\r\n" + e2.getMessage());
					/*try {
						// 读取所有文章
						BufferedReader br = new BufferedReader(
								new InputStreamReader(new FileInputStream("json.txt"), "utf-8"));
						String str = null;
						StringBuilder sbf = new StringBuilder();
						while ((str = br.readLine()) != null) {
							sbf.append(str);
						}
						br.close();

						jsonObject = JSON.parseObject(sbf.toString());


						System.out.println(jsonObject);
					} catch (Exception e3) {
						e3.printStackTrace();
					}*/

                }

            }

        }
        Date now = new Date();
        if (jsonObject != null) {
            JSONArray jsonArray = jsonObject.getJSONArray("list");
            if(jsonArray != null && jsonArray.size() > 0){
                int size = jsonArray.size();
                JSONObject newsJsonObject = null;
                for (int j = 0; j < size; j++) {
                    newsJsonObject = jsonArray.getJSONObject(j);
                    if (newsJsonObject != null) {

                        Date pubdate = null;
                        try {
                            Long time = newsJsonObject.getJSONObject("comm_msg_info").getLong("datetime")*1000;
                            pubdate = new Date(time);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        JSONObject news = newsJsonObject.getJSONObject("app_msg_ext_info");

                        if (news == null) {
                            continue;
                        }


                        String link = news.getString("content_url");

                        WxBizNews wxBizNewsF = null;
                        if (link != null && !link.equals("")) {
                            wxBizNewsF = new WxBizNews();
                            wxBizNewsF.setId(IdGenerateUtil.get().nextId());
                            wxBizNewsF.setAddtime(now);
                            wxBizNewsF.setPubtime(pubdate);
                            wxBizNewsF.setDelflag(0);

                            getProp(wxBizNewsF,news);

                            list.add(wxBizNewsF);
                        }

                        JSONArray array = news.getJSONArray("multi_app_msg_item_list");
                        if (array!= null && array.size()>0) {
                            for (int jj = 0; jj < array.size(); jj++) {
                                JSONObject object = array.getJSONObject(jj);

                                if (object == null) {
                                    continue;
                                }


                                String l = object.getString("content_url");


                                if (l != null && !l.equals("")) {
                                    WxBizNews wxBizNews = new WxBizNews();
                                    wxBizNews.setId(IdGenerateUtil.get().nextId());
                                    wxBizNews.setPubtime(pubdate);
                                    wxBizNews.setAddtime(now);
                                    wxBizNews.setDelflag(0);
                                    wxBizNews.setFaId(wxBizNewsF == null ? 0L : wxBizNewsF.getId());

                                    getProp(wxBizNews,object);

                                    list.add(wxBizNews);
                                }
                            }
                        }

                    } else {
                        System.out.println("文章获取失败！");
                    }
                }
            }else{
                System.out.println("获取文章列表失败！");
            }
        }else{
            System.out.println("json解析失败！");
        }

        return list;
    }

    private static void getProp(WxBizNews wxBizNews, JSONObject news) {

        String link = news.getString("content_url");
        Map<String, String> paramMap = StringUtil.getAllParam(link.replace("==", "######"));
        String biz = paramMap.get("__biz").replace("######", "==");
        String mid = paramMap.get("mid");
        String sn = paramMap.get("sn");
        String idx = paramMap.get("idx");
        if(link.contains("?")){
            if(!StringUtil.isEmpty(biz) && !StringUtil.isEmpty(mid) && !StringUtil.isEmpty(sn) && !StringUtil.isEmpty(idx)){
                link = link.substring(0, link.indexOf("?") + 1) + "__biz=" + biz + "&mid=" + mid + "&idx=" + idx + "&sn=" + sn;
            }else if(link.contains("&chksm=")){
                link = link.substring(0,link.indexOf("&chksm="));
            }
        }
        wxBizNews.setContentUrl(link);
        wxBizNews.setBiz(biz);
        wxBizNews.setMid(mid);
        wxBizNews.setSn(sn);
        wxBizNews.setIdx(idx);

        String title = news.getString("title");
        title = title==null ? null : title.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]","*");
        title = title.length()>100 ? title.substring(0,100) : title;
        wxBizNews.setTitle(title);
        String digest = news.getString("digest");
        digest = digest==null ? null : digest.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]","*");
        wxBizNews.setDigest(digest);
        wxBizNews.setSourceUrl(news.getString("source_url"));
        wxBizNews.setFileid(news.getLong("fileid"));
        wxBizNews.setCover(news.getString("cover"));
        wxBizNews.setItemShowType(news.getInteger("item_show_type"));
        wxBizNews.setDuration(news.getLong("duration"));
        wxBizNews.setIsMulti(news.getInteger("is_multi"));
        wxBizNews.setSubtype(news.getInteger("subtype"));

    }

    public static Map<String, Integer> parseJson(String resjson) {
        Integer read_num = null;
        Integer like_num = null;
        Integer old_like_num = null;
        try {
            JSONObject object = JSON.parseObject(resjson);
            JSONObject o1 = object.getJSONObject("appmsgstat");
            read_num = o1.getInteger("read_num");
            like_num = o1.getInteger("like_num");
            old_like_num = o1.getInteger("old_like_num");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("json长度超限，字符串提取");
            int lni = resjson.indexOf("\"read_num\":");
            if (lni >= 0) {
                String lniStrTemp = resjson.substring(lni + 11, lni + 21);
                lni = lniStrTemp.indexOf(",");
                if (lni >= 0) {
                    String read_numStr = lniStrTemp.substring(0, lni);
                    if (StringUtil.isNumeric(read_numStr)) {
                        read_num  = Integer.valueOf(read_numStr);
                    }
                }
            }
            lni = resjson.indexOf("\"like_num\":");
            if (lni >= 0) {
                String lniStrTemp = resjson.substring(lni + 11, lni + 20);
                lni = lniStrTemp.indexOf(",");
                if (lni >= 0) {
                    String like_numStr = lniStrTemp.substring(0, lni);
                    if (StringUtil.isNumeric(like_numStr)) {
                        like_num  = Integer.valueOf(like_numStr);
                    }
                }
            }
            lni = resjson.indexOf("\"old_like_num\":");
            if (lni >= 0) {
                String lniStrTemp = resjson.substring(lni + 11, lni + 20);
                lni = lniStrTemp.indexOf(",");
                if (lni >= 0) {
                    String old_like_numStr = lniStrTemp.substring(0, lni);
                    if (StringUtil.isNumeric(old_like_numStr)) {
                        old_like_num  = Integer.valueOf(old_like_numStr);
                    }
                }
            }
        }

        System.out.println("阅读量：" + read_num);
        System.out.println("点赞：" + old_like_num);
        System.out.println("在看：" + like_num);

        Map<String, Integer> appmsgMap = new HashMap<String, Integer>();
        appmsgMap.put("readNum", read_num);
        appmsgMap.put("likeNum", old_like_num);
        appmsgMap.put("onlookNum", like_num);

        return appmsgMap;
    }
}
